package net.lesscoding.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import feign.FeignException;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.lesscoding.entity.order.OrderTbl;
import net.lesscoding.feign.AccountClient;
import net.lesscoding.feign.StorageClient;
import net.lesscoding.mapper.OrderMapper;
import org.springframework.stereotype.Service;

/**
 * @author eleven
 * @date 2025/4/16 13:57
 * @apiNote
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OrderService extends ServiceImpl<OrderMapper, OrderTbl> {

    private final OrderMapper orderMapper;
    private final StorageClient storageClient;
    private final AccountClient accountClient;

    /**
     * 创建订单
     * 1. 扣减库存
     * 2. 扣减余额
     *
     * @param order 订单
     * @return 订单ID
     */
    @GlobalTransactional(rollbackFor = Throwable.class)
    public Integer createOrder(OrderTbl order) {
        orderMapper.insert(order);
        try {
        accountClient.deduct(order.getUserId(), order.getMoney());
        storageClient.deduct(order.getGoodsCode(), order.getCount());
        } catch (FeignException e) {
            log.error("扣减库存或扣减余额失败, 订单回滚, 原因: {}", e.contentUTF8(), e);
            throw new RuntimeException(e.contentUTF8(), e);
        }
        return order.getId();
    }
}
